<script setup lang="ts">
import Taro from "@tarojs/taro";

import ByTag from "@/components/ui/ByTag.vue";
import ByButton from "@/components/ui/ByButton.vue";
import ViewList from "@/components/common/ViewList.vue";
import ContentBox from "@/pages/index/components/ContentBox.vue";

import useEnum from "@/hooks/useEnum";
import useList from "@/hooks/useList";
import useFetch from "@/hooks/useFetch";
import ApiMerchant from "@/api/merchant";
import { staffTypeOptions } from "@/utils/dictionary";
import { TMerchantStaff } from "@/global";

const { mid } = defineProps<{
  mid: number;
}>();

const { get: getStaffType } = useEnum(staffTypeOptions);

// 获取商户员工列表
const { loading, list, resetToFirst } = useList<TMerchantStaff>(
  ApiMerchant.getMerchantStaffList,
  { search: { merchant_id: mid } }
);

const { run: updateStatus } = useFetch(ApiMerchant.updateMerchantStaffStatus, {
  immediate: false,
  showLoading: true,
  onSuccess() {
    Taro.showLoading({ title: "更新成功" });
    resetToFirst();
  },
});

// 禁用/解禁员工 二次确认
const handleStaffStatus = async ({
  id,
  staff_name,
  status,
}: TMerchantStaff) => {
  const nextStatus = status == 2 ? 1 : 2;
  const text = nextStatus == 2 ? "禁用" : "恢复";

  const { confirm } = await Taro.showModal({
    title: "提示",
    content: `确定${text}员工“${staff_name}”状态？`,
  });

  if (confirm) {
    updateStatus({ id, status: nextStatus });
  }
};
</script>

<template>
  <ViewList :loading="loading" :is-empty="list.length == 0">
    <ContentBox class="mt-4" hideBgImg v-for="item in list" :key="item.id">
      <view class="flex justify-between items-center p-3">
        <view class="flex-auto">
          <view class="flex items-center">
            <text class="text-2xl pr-3">{{ item?.staff_name }}</text>

            <ByTag rounded :type="getStaffType(item.staff_type)?.color">
              {{ getStaffType(item.staff_type)?.name }}
            </ByTag>
          </view>
          <view class="mt-2 text-lg text-[#888]">{{ item?.mobile }}</view>
        </view>

        <view v-if="item.staff_type != 1">
          <ByButton
            size="small"
            :type="item.status === 1 ? 'error' : 'primary'"
            @tap="handleStaffStatus(item)"
          >
            {{ item.status == 1 ? "禁用TA" : "恢复" }}
          </ByButton>

          <view class="mt-1 text-third text-xs" v-if="item.status !== 1">
            {{ item.status == 2 ? "已被禁用" : "已离职" }}
          </view>
        </view>
      </view>
    </ContentBox>
  </ViewList>
</template>
